import os
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from tortoise import Tortoise
from tortoise.exceptions import DoesNotExist, IntegrityError, DBConnectionError
from dotenv import load_dotenv

# 获取.env文件路径
load_dotenv()


# Mysql数据库配置
DB_ORM_CONFIG = {
    "connections": {
        "base": {
            "engine": "tortoise.backends.mysql",
            "credentials": {
                "host": os.getenv("BASE_HOST", "127.0.0.1"),
                "user": os.getenv("BASE_USER", "root"),
                "password": os.getenv("BASE_PASS", "root"),
                "port": int(os.getenv("BASE_PORT", "3306")),
                "database": os.getenv("BASE_DATABASE", "fastapi"),
            },
        }
    },
    "apps": {
        "base": {
            "models": ["app.models.base"],
            "default_connection": "base",
        }
    },
    "use_tz": False,
    "timezone": "Asia/Shanghai",
}

# 初始化数据库
async def init_mysql(app: FastAPI):
    try:
        print("🔌 正在初始化 Tortoise ORM...")
        await Tortoise.init(config=DB_ORM_CONFIG)
        print("✅ Tortoise ORM 初始化成功")

        # 可选：自动生成表结构（仅用于开发）
        await Tortoise.generate_schemas()
        print(f"✅ 数据库已生成")

        # 注册全局异常处理器
        register_exception_handlers(app)

    except Exception as e:
        print(f"❌ 初始化数据库失败: {e}")
        raise

# 替代 add_exception_handlers=True 的手动异常处理
def register_exception_handlers(app: FastAPI):
    @app.exception_handler(DoesNotExist)
    async def handle_does_not_exist(request: Request, exc: DoesNotExist):
        return JSONResponse(status_code=404, content={"error": str(exc)})

    @app.exception_handler(IntegrityError)
    async def handle_integrity_error(request: Request, exc: IntegrityError):
        return JSONResponse(status_code=400, content={"error": str(exc)})

    @app.exception_handler(DBConnectionError)
    async def handle_db_connection_error(request: Request, exc: DBConnectionError):
        return JSONResponse(status_code=503, content={"error": "数据库连接失败，请检查配置或服务状态"})
